<!-- CreateOrder.vue - 创建订单页面 -->
<template>
  <div class="create-order-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-button 
        type="text" 
        @click="goBack" 
        class="back-btn"
        :icon="ArrowLeft"
      >
        返回商品详情
      </el-button>
      <h2 class="page-title">确认订单</h2>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 订单内容 -->
    <div v-else-if="product" class="order-content">
      <!-- 商品信息 -->
      <el-card class="product-card" shadow="hover">
        <template #header>
          <div class="card-title">
            <el-icon class="title-icon"><Box /></el-icon>
            <span>商品信息</span>
          </div>
        </template>
        
        <div class="product-info">
          <div class="product-image">
            <el-image
              :src="getFirstImage(product.coverList)"
              :alt="product.productName"
              fit="cover"
              class="product-img"
              :preview-src-list="getImageList(product.coverList)"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
          </div>
          
          <div class="product-details">
            <h3 class="product-name">{{ product.productName }}</h3>
            <div class="product-meta">
              <span class="old-level">
                <el-tag :type="getOldLevelType(product.oldLevel)" size="small">
                  {{ product.oldLevel }}成新
                </el-tag>
              </span>
              <span class="price">¥{{ product.price }}</span>
            </div>
            <p class="product-desc">{{ product.productDetail || '暂无描述' }}</p>
          </div>
        </div>
      </el-card>

      <!-- 订单信息 -->
      <el-card class="order-form-card" shadow="hover">
        <template #header>
          <div class="card-title">
            <el-icon class="title-icon"><Document /></el-icon>
            <span>订单信息</span>
          </div>
        </template>
        
        <el-form
          ref="orderFormRef"
          :model="orderForm"
          :rules="orderRules"
          label-width="100px"
          class="order-form"
        >
          <el-form-item label="购买数量" prop="quantity">
            <el-input-number
              v-model="orderForm.quantity"
              :min="1"
              :max="1"
              :disabled="true"
              controls-position="right"
            />
            <span class="form-tip">二手商品数量固定为1</span>
          </el-form-item>

          <el-form-item label="收货人" prop="buyerName">
            <el-input
              v-model="orderForm.buyerName"
              placeholder="请输入收货人姓名"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="buyerPhone">
            <el-input
              v-model="orderForm.buyerPhone"
              placeholder="请输入联系电话"
              maxlength="20"
            />
          </el-form-item>

          <el-form-item label="收货地址" prop="buyerAddress">
            <el-input
              v-model="orderForm.buyerAddress"
              type="textarea"
              :rows="3"
              placeholder="请输入详细的收货地址"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="订单备注" prop="detail">
            <el-input
              v-model="orderForm.detail"
              type="textarea"
              :rows="2"
              placeholder="选填，如：请尽快发货、包装要求等"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 订单汇总 -->
      <el-card class="order-summary-card" shadow="hover">
        <template #header>
          <div class="card-title">
            <el-icon class="title-icon"><Money /></el-icon>
            <span>订单汇总</span>
          </div>
        </template>
        
        <div class="summary-content">
          <div class="summary-row">
            <span class="label">商品单价：</span>
            <span class="value">¥{{ product.price }}</span>
          </div>
          <div class="summary-row">
            <span class="label">购买数量：</span>
            <span class="value">{{ orderForm.quantity }}</span>
          </div>
          <div class="summary-row total-row">
            <span class="label">实付款：</span>
            <span class="value total-amount">¥{{ totalAmount }}</span>
          </div>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button size="large" @click="goBack">
          返回修改
        </el-button>
        <el-button 
          type="primary" 
          size="large" 
          @click="submitOrder"
          :loading="submitting"
          class="submit-btn"
        >
          <el-icon><CreditCard /></el-icon>
          {{ submitting ? '创建中...' : '确认下单' }}
        </el-button>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="商品信息加载失败">
        <el-button type="primary" @click="goBack">
          返回商品详情
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productAPI, orderAPI } from '@/api'
import {
  ArrowLeft,
  Box,
  Picture,
  Document,
  Money,
  CreditCard
} from '@element-plus/icons-vue'

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const submitting = ref(false)
const product = ref(null)
const orderFormRef = ref(null)

// 订单表单数据
const orderForm = ref({
  productId: null,
  quantity: 1,
  buyerName: '',
  buyerPhone: '',
  buyerAddress: '',
  detail: ''
})

// 表单验证规则
const orderRules = {
  buyerName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
  ],
  buyerPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  buyerAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 10, max: 200, message: '地址长度在10到200个字符', trigger: 'blur' }
  ]
}

// 计算属性
const totalAmount = computed(() => {
  if (!product.value) return '0.00'
  return (product.value.price * orderForm.value.quantity).toFixed(2)
})

// 方法
const goBack = () => {
  router.go(-1)
}

const getFirstImage = (coverList) => {
  try {
    if (typeof coverList === 'string') {
      const images = JSON.parse(coverList)
      return images.length > 0 ? images[0] : getDefaultImage()
    } else if (Array.isArray(coverList)) {
      return coverList.length > 0 ? coverList[0] : getDefaultImage()
    }
    return getDefaultImage()
  } catch {
    return getDefaultImage()
  }
}

const getImageList = (coverList) => {
  try {
    if (typeof coverList === 'string') {
      return JSON.parse(coverList)
    } else if (Array.isArray(coverList)) {
      return coverList
    }
    return []
  } catch {
    return []
  }
}

const getDefaultImage = () => {
  return ''
}

const getOldLevelType = (level) => {
  if (level >= 8) return 'success'
  if (level >= 6) return 'warning'
  if (level >= 4) return 'info'
  return 'danger'
}

const loadProduct = async () => {
  try {
    loading.value = true
    const productId = route.params.id
    const response = await productAPI.getProductDetail(productId)
    
    if (response.code === 0) {
      product.value = response.data
      orderForm.value.productId = parseInt(productId)
    } else {
      ElMessage.error(response.message || '商品信息加载失败')
    }
  } catch (error) {
    console.error('加载商品信息失败:', error)
    ElMessage.error('商品信息加载失败')
  } finally {
    loading.value = false
  }
}

const submitOrder = async () => {
  try {
    // 表单验证
    await orderFormRef.value.validate()
    
    // 确认对话框
    await ElMessageBox.confirm(
      `确认下单购买"${product.value.productName}"？\n实付款：¥${totalAmount.value}`,
      '确认下单',
      {
        confirmButtonText: '确认下单',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    submitting.value = true
    
    // 提交订单
    console.log('CreateOrder: 提交订单数据:', orderForm.value)
    const response = await orderAPI.createOrder(orderForm.value)
    console.log('CreateOrder: 订单创建响应:', response)
    
    if (response.code === 0) {
      ElMessage.success('订单创建成功！')
      
      // 更新商品状态为已售出
      try {
        await productAPI.updateProductStatus(orderForm.value.productId, 'sold')
      } catch (error) {
        ElMessage.warning('订单创建成功，但商品状态更新失败，请联系管理员')
      }
      
      // 触发全局事件，通知商品详情页面刷新状态
      window.dispatchEvent(new CustomEvent('orderCreated', {
        detail: { productId: orderForm.value.productId }
      }))
      
      // 如果有返回的订单ID，跳转到订单详情页
      if (response.data && response.data.id) {
        router.push(`/gear/order/${response.data.id}`)
      } else {
        // 否则跳转到我的购买页面
        router.push('/gear/buying')
      }
    } else {
      console.error('CreateOrder: 订单创建失败:', response)
      ElMessage.error(response.message || '订单创建失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('创建订单失败:', error)
      ElMessage.error('订单创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 生命周期
onMounted(() => {
  loadProduct()
})
</script>

<style scoped>
.create-order-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 0;
}

.back-btn {
  margin-right: 16px;
  color: #409eff;
  font-size: 14px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.loading-container {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-card,
.order-form-card,
.order-summary-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.product-card:hover,
.order-form-card:hover,
.order-summary-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.title-icon {
  margin-right: 8px;
  color: #409eff;
}

.product-info {
  display: flex;
  gap: 16px;
}

.product-image {
  flex-shrink: 0;
}

.product-img {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #c0c4cc;
  font-size: 12px;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.price {
  font-size: 20px;
  font-weight: 600;
  color: #f56c6c;
}

.product-desc {
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.order-form {
  max-width: 600px;
}

.form-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 12px;
}

.summary-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.summary-row:not(:last-child) {
  border-bottom: 1px solid #f0f0f0;
}

.total-row {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-top: 2px solid #e4e7ed;
  margin-top: 8px;
  padding-top: 16px;
}

.total-amount {
  color: #f56c6c;
  font-size: 20px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.submit-btn {
  min-width: 160px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}

.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-order-page {
    padding: 16px;
  }
  
  .product-info {
    flex-direction: column;
  }
  
  .product-img {
    width: 100%;
    height: 200px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .submit-btn {
    width: 100%;
  }
}
</style>
